﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.AdvTree;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util;
using PlanningGIS.ManageUtility.Modules;
using PlanningGIS.ManageUtility;
using PlanningGIS.Util.IO;

namespace PlanningGIS.Manager
{
    /// <summary>
    /// 配图模板
    /// </summary>
    public partial class CtlMXD : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public CtlMXD()
        {
            InitializeComponent();
        }
        
        /// <summary>
        /// 
        /// </summary>
        private BillCommands _Commands;

        /// <summary>
        /// Gets or sets the commands associated with the control.
        /// </summary>
        public BillCommands Commands
        {
            get { return _Commands; }
            set
            {
                if (value != _Commands)
                {
                    BillCommands oldValue = _Commands;
                    _Commands = value;
                    OnCommandsChanged(oldValue, value);
                }
            }
        }

        /// <summary>
        /// Called when Commands property has changed.
        /// </summary>
        /// <param name="oldCmd">Old property value</param>
        /// <param name="newCmd">New property value</param>
        protected virtual void OnCommandsChanged(BillCommands oldCmd, BillCommands newCmd)
        {
            btnSave.Command = newCmd != null ? newCmd.MXDCommands .Save : null;
            btnClose.Command = newCmd != null ? newCmd.MXDCommands.Cancel : null;
        }

        /// <summary>
        /// 当前的操作类型
        /// </summary>
        private zjgisOperateType _OperateType = zjgisOperateType.UnKnow;

        /// <summary>
        /// 加载控件
        /// </summary>
        public void LoadControl()
        {
            _OperateType = zjgisOperateType.UnKnow;
            UpdateStatus();
            this.Cursor = Cursors.WaitCursor;
            try
            {
                mxdTree1.BindData();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 更新按钮的操作状态
        /// </summary>
        private void UpdateStatus()
        {
            switch (_OperateType)
            {
                case zjgisOperateType.Add:
                    txtName.Text = "";
                    txtName.ReadOnly = false;
                    txtName.Tag = null;
                    txtName.ButtonCustom.Enabled = true;
                    btnAdd.Enabled = false;
                    btnUpdate.Enabled = false;
                    btnSave.Enabled = true;
                    break;
                case zjgisOperateType.Update:
                    txtName.ReadOnly = false;
                    txtName.ButtonCustom.Enabled = true;
                    btnAdd.Enabled = false;
                    btnUpdate.Enabled = false;
                    btnSave.Enabled = true;
                    break;
                case zjgisOperateType.UnKnow:
                default :
                    txtName.ReadOnly = true;
                    txtName.ButtonCustom.Enabled = false;
                    btnAdd.Enabled = true;
                    btnUpdate.Enabled = true;
                    btnSave.Enabled = false;
                    break;
            }
        }

        /// <summary>
        /// 选择MXD
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPath_ButtonCustomClick(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            dlg.Filter = "地图配图文件(*.mxd;*.lyr)|*.mxd;*.lyr|所有文件(*.*)|*.*";
            try
            {
                if (dlg.ShowDialog(this.ParentForm) == DialogResult.OK)
                {
                    if (string.IsNullOrWhiteSpace(txtName.Text))
                        txtName.Text = Path.GetFileNameWithoutExtension(dlg.FileName);
                    byte[] c = FileHelper.ReadByte(dlg.FileName);
                    if (_OperateType == zjgisOperateType.Add)
                    {
                        MXDInfo m = new MXDInfo()
                        {
                            ID = Guid.NewGuid().ToString(),
                            Name = txtName.Text,
                            Content = c
                        };
                        txtName.Tag = m;
                    }
                    else if (_OperateType == zjgisOperateType.Update)
                    {
                        ((MXDInfo)txtName.Tag).Content = c;
                    }

                }
            }
            catch(Exception  ex)
            {
                MsgHelper.ShowErrorMsgbox("错误提示： "+ex.Message);
            }
            
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            _OperateType = zjgisOperateType.Add;
            UpdateStatus();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            _OperateType = zjgisOperateType.Update;
            UpdateStatus();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (mxdTree1.SelectedNodes.Count == 0)
            {
                MsgHelper.ShowInfomationMsgbox("请先选择要删除的模板，按住Ctrl键可以多选");
                return;
            }
            if (MsgHelper.ShowYesOrNoQueryMsgBox("是否确定要删除已选择的模板？") != DialogResult.Yes) return;
            List<string> ids = new List<string>();
            List<Node> nds = new List<Node>();
            foreach (Node r in mxdTree1.SelectedNodes)
            {
                ids.Add(r.Name.ToString());
                nds.Add(r);
            }
            try
            {
                int rst = ManageHelper.DBContext.Delete("MXDInfo", ids);
                if (rst >= 0)
                {
                    foreach (Node r in nds)
                    {
                        mxdTree1.Nodes.Remove(r);
                    }
                    MsgHelper.ShowInfomationMsgbox("删除成功");
                }
                else
                {
                    MsgHelper.ShowErrorMsgbox("删除失败");
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mxdTree1_AfterNodeSelect(object sender, DevComponents.AdvTree.AdvTreeNodeEventArgs e)
        {
            if (mxdTree1.SelectedNode == null)
            {
                txtName.Text = "";
                txtName.Tag = null;
                return;
            }
            MXDInfo d = (MXDInfo)mxdTree1.SelectedNode.Tag;
            txtName.Text = d.Name;
            txtName.Tag = d;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mxdTree1_AfterCheck(object sender, DevComponents.AdvTree.AdvTreeCellEventArgs e)
        {
            
            if (e.Action != eTreeAction.Mouse && e.Action != eTreeAction.Keyboard) return;
            if (mxdTree1.SelectedNode == null) return;
            MXDInfo d = (MXDInfo)mxdTree1.SelectedNode.Tag;
            //先触发点击事件，在触发值改变事件
            d.SetEnable(mxdTree1.SelectedNode.Checked);
            try
            {
                int cnt = ManageHelper.DBContext.Update<MXDInfo>(d, "id", d.ID);
                ((MXDInfo)mxdTree1.SelectedNode.Tag).SetEnable(d.GetEnable());
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
        }
        
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtName.Text) || txtName.Tag == null)
            {
                MsgHelper.ShowInfomationMsgbox("模板信息不完整，请重新填写");
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            MXDInfo d = (MXDInfo)txtName.Tag;              
            d.SetEnable(true);
            try
            {
                int cnt = 0;
                if (_OperateType == zjgisOperateType.Add)
                {
                    cnt = ManageHelper.DBContext.Insert<MXDInfo>(d);
                    if (cnt > 0) mxdTree1.AddNode(d, null);
                }
                else if (_OperateType ==  zjgisOperateType.Update)
                {
                    cnt = ManageHelper.DBContext.Update<MXDInfo>(d, "id", d.ID);
                    if (cnt > 0)
                    {
                        mxdTree1.SelectedNode.Text = d.Name;
                        mxdTree1.SelectedNode.Tag = d;
                    }
                }
                if (cnt < 1)
                {
                    MsgHelper.ShowErrorMsgbox("操作失败:" + ManageHelper.DBContext.Message);
                    return;
                }
                _OperateType = zjgisOperateType.UnKnow;
                UpdateStatus();
                MsgHelper.ShowInfomationMsgbox("操作成功");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("操作失败:" + ex.ToString());
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }            
        }

        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {

        }

    }
}
